package com.adlotto2.lcdns.util;

import java.lang.ref.WeakReference;
import java.util.List;

import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;

/**
 * RecycleUtils - 메모리 해제 
 * View에 붙어있는 View의 child를 리커시브로 null로 설정해주는 메소드
 */
public class RecycleUtils {

	private RecycleUtils() {
	};

	public static void recursiveRecycle(View root) {
		if (root == null)
			return;

		root.setBackgroundDrawable(null);

		if (root instanceof ViewGroup) {
			CNCronosLog.d("RecycleUtils", "root instanceof ViewGroup");
			ViewGroup group = (ViewGroup) root;
			int count = group.getChildCount();
			for (int i = 0; i < count; i++) {
				recursiveRecycle(group.getChildAt(i));
			}

			if (!(root instanceof AdapterView)) {
				CNCronosLog.d("RecycleUtils", "!(root instanceof AdapterView)");
				group.removeAllViews();
			}
		}
		
		Drawable d = root.getBackground();
		
		if (root instanceof ImageView) {
			CNCronosLog.d("RecycleUtils", "root instanceof ImageView");
			ImageView imageView = (ImageView)root;
    		d = imageView.getDrawable();            
    		if (d != null) {                
    			d.setCallback(null);
    		}                         
    		
    		imageView.setImageDrawable(null);
		}

		root = null;
		System.gc();
		return;
	}

	public static void recursiveRecycle(List<WeakReference<View>> recycleList) {
		for (WeakReference<View> ref : recycleList) {
			recursiveRecycle(ref.get());
		}
	}
}